package com.gosuncn.config.pdf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用于处理java调用系统命令读取输出到系统控制台
 * 的流，避免程序阻塞挂起
 */
public class ProcessStreamHandler {

    public static void handle(final Process process) {
        if (process == null) {
            return;
        }
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                consumeInputStream(process.getInputStream());
            }
        });
        executor.submit(new Runnable() {
            @Override
            public void run() {
                consumeInputStream(process.getErrorStream());
            }
        });
        executor.shutdown();
    }

    private static void consumeInputStream(InputStream is) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line.toString());
            }
        } catch (IOException e) {
            
        }
    }

}
